package com.cz.nongyetongv5.activity;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.PhotoDetailPageAdapter;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.custom.photoview.PhotoViewAttacher.OnPhotoTapListener;
import com.cz.nongyetongv5.custom.wheelview.Utils;

public class PhotoDetailActivity extends Activity implements
		OnPhotoTapListener, OnClickListener {

	// 显示详细照片的控件
	private ViewPager vpPhotoViewPager = null;

	private PhotoDetailPageAdapter vpPhotoDetailViewPagerAdapter = null;

	/**
	 * 照片的数据
	 */
	private List<Photo> photos = null;

	/**
	 * 返回按钮
	 */
	private ViewGroup btnBack = null;

	/**
	 * 删除按钮
	 */
	private Button btnPhotoDelete = null;

	/**
	 * 照片详细信息按钮
	 */
	private Button btnPhotoDetailInfo = null;

	/**
	 * 评论按钮
	 */
	private View btnComment = null;

	/**
	 * 顶部标题工具栏的布局对象
	 */
	private LinearLayout rlTitleBar = null;

	/**
	 * 底部工具栏的对象
	 */
	private LinearLayout llBottomBar = null;

	/**
	 * 图片的标题
	 */
	private TextView tvPhotoDetailTitle = null;

	/**
	 * 标题fadeIn进入动画
	 */
	private Animation titlefadeIn = null;

	/**
	 * 底部fadeIn进入动画
	 */
	private Animation bottomfadeIn = null;

	/**
	 * 标题退出动画
	 */
	private Animation titlefadeOut = null;

	/**
	 * 底部退出动画
	 */
	private Animation bottomfadeOut = null;

	/**
	 * 是否上传
	 */
	private CheckBox cbShangChuan = null;

	private TextView tvJingWei = null;

	@Override
	protected void onDestroy() {
		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().remove(this);

		// TODO Auto-generated method stub
		super.onDestroy();
	}
	private String type="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		InitApplication initApplication = (InitApplication) getApplicationContext();

		initApplication.getActivities().add(this);

		setContentView(R.layout.photo_detail);

		tvJingWei = (TextView) findViewById(R.id.tvPoint);
		tvJingWei.setClickable(false);

		// 拿到数据Intent
		Intent to_detailphoto_intent = getIntent();
		try{
			type=to_detailphoto_intent.getExtras().getString("type");
		}catch(java.lang.Exception e ){

		}
		// 获取数据
		photos = (List<Photo>) to_detailphoto_intent
				.getSerializableExtra("photos");

		// 去掉最后一个数据,最后一个数据为更多
		photos.remove(photos.size() - 1);

		// 获得点击的下标
		int click_index = to_detailphoto_intent.getIntExtra(
				"click_photo_index", 0);

		// 取得ViewPager对象
		this.vpPhotoViewPager = (ViewPager) findViewById(R.id.vpPhotoViewPager);

		// 详细ViewPager的适配器
		vpPhotoDetailViewPagerAdapter = new PhotoDetailPageAdapter(photos, this);

		// 设置适配器
		vpPhotoViewPager.setAdapter(vpPhotoDetailViewPagerAdapter);

		vpPhotoViewPager.setCurrentItem(click_index);

		// 返回按钮
		btnBack = (ViewGroup) findViewById(R.id.btnBack);
		// 绑定单击事件
		btnBack.setOnClickListener(this);

		// 删除按钮
		btnPhotoDelete = (Button) findViewById(R.id.btnPhotoDelete);
		btnPhotoDelete.setOnClickListener(this);

		// 详细信息按钮
		btnPhotoDetailInfo = (Button) findViewById(R.id.btnPhotoDetailInfo);
		btnPhotoDetailInfo.setOnClickListener(this);

		/**
		 * 当点击评论的时候
		 */
		btnComment = findViewById(R.id.btnComment);

		btnComment.setOnClickListener(this);

		cbShangChuan = (CheckBox) findViewById(R.id.cbShangChuan);

		cbShangChuan.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
										 boolean isChecked) {

				int postion = vpPhotoViewPager.getCurrentItem();


				if(type!=null&&type.equals("single")){
					for(int i=0;i<photos.size();i++){
						photos.get(i).setUpload(false);
					}
				}
				Photo photo = photos.get(postion);
				photo.setUpload(isChecked);

				if (isChecked) {
					buttonView.setText(getString(R.string.xuanzhong));
				} else {
					buttonView.setText(getString(R.string.weixuanzhong));
				}

			}
		});

		// 顶部的标题对象
		rlTitleBar = (LinearLayout) findViewById(R.id.rlTitleBar);

		// 底部共居然对象
		llBottomBar = (LinearLayout) findViewById(R.id.llBottomBar);

		/**
		 * 图片的标题
		 */
		tvPhotoDetailTitle = (TextView) findViewById(R.id.tvPhotoDetailTitle);

		// 设置默认标题
		tvPhotoDetailTitle.setText("图片(" + (click_index + 1) + "/"
				+ PhotoDetailActivity.this.photos.size() + ")");

		// 手动初始化第一个页面是否上传
		Photo photo = photos.get(click_index);
		cbShangChuan.setChecked(photo.isUpload());

		if (photo.getLatitude()!=null&& photo.getLongitude()!=null&&
				photo.getLatitude() > 1 && photo.getLongitude() > 1) {

			BigDecimal a = new BigDecimal(photo.getLongitude());
			double longite = a.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

			BigDecimal b = new BigDecimal(photo.getLatitude());
			double latitude = b.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

			tvJingWei.setText(longite+ " , "
					+ latitude);

		} else {
			tvJingWei.setText("未知 , 未知");
		}

		// 当pager改变的时候
		vpPhotoViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int postion) {
				// 设置标题
				tvPhotoDetailTitle.setText("图片(" + (postion + 1) + "/"
						+ PhotoDetailActivity.this.photos.size() + ")");

				Photo photo = photos.get(postion);

				cbShangChuan.setChecked(photo.isUpload());

				if (photo.getLatitude() != null && photo.getLatitude() > 1
						&& photo.getLongitude() != null
						&& photo.getLongitude() > 1) {
					tvJingWei.setVisibility(View.VISIBLE);
					tvJingWei.setText(photo.getLongitude() + " , "
							+ photo.getLatitude());
				} else {

					tvJingWei.setText("未知 , 未知");
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		// 动画的加载
		titlefadeIn = AnimationUtils.loadAnimation(PhotoDetailActivity.this,
				R.anim.photodetail_title_anim_fadein);
		bottomfadeIn = AnimationUtils.loadAnimation(PhotoDetailActivity.this,
				R.anim.bottom_window_anim_move);

		titlefadeIn.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				// 如果为隐藏
				if (rlTitleBar.getVisibility() == View.GONE) {
					// 动画加载前显示
					rlTitleBar.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
			}
		});

		bottomfadeIn.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				// 如果为隐藏
				if (llBottomBar.getVisibility() == View.GONE) {
					// 动画加载前显示
					llBottomBar.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
			}
		});

		titlefadeOut = AnimationUtils.loadAnimation(PhotoDetailActivity.this,
				R.anim.photodetail_title_anim_fadeout);
		titlefadeOut.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {

				// 动画完成后设置隐藏
				if (rlTitleBar.getVisibility() == View.VISIBLE) {
					// 动画加载前显示
					rlTitleBar.setVisibility(View.GONE);
				}
			}
		});

		bottomfadeOut = AnimationUtils.loadAnimation(PhotoDetailActivity.this,
				R.anim.bottom_window_anim_out);
		bottomfadeOut.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {

				// 动画完成后设置隐藏
				if (llBottomBar.getVisibility() == View.VISIBLE) {
					// 动画加载前显示
					llBottomBar.setVisibility(View.GONE);
				}
			}
		});

		// 设置进场动画
		rlTitleBar.clearAnimation();
		rlTitleBar.setAnimation(titlefadeIn);
		titlefadeIn.startNow();

		llBottomBar.clearAnimation();
		llBottomBar.setAnimation(bottomfadeIn);
		bottomfadeIn.startNow();

	}

	@Override
	public void onPhotoTap(View view, float x, float y) {

		/**
		 * 获得index
		 */
		int index = vpPhotoViewPager.indexOfChild(view);

		if (index > -1) {

			// 如果工具栏为显示
			if (rlTitleBar.getVisibility() == View.VISIBLE) {
				rlTitleBar.clearAnimation();
				rlTitleBar.setAnimation(titlefadeOut);
				titlefadeOut.start();

			} else {
				rlTitleBar.clearAnimation();
				rlTitleBar.setAnimation(titlefadeIn);
				titlefadeIn.start();
			}

			// 如果工具栏为显示
			if (llBottomBar.getVisibility() == View.VISIBLE) {
				llBottomBar.clearAnimation();
				llBottomBar.setAnimation(bottomfadeOut);
				bottomfadeOut.start();

			} else {
				llBottomBar.clearAnimation();
				llBottomBar.setAnimation(bottomfadeIn);
				bottomfadeIn.start();
			}

		}
	}

	@Override
	public void onClick(View v) {

		// 如果是返回按钮
		if (v == btnBack) {
			returnData();
			// 将编辑好的数据返回
			PhotoDetailActivity.this.finish();
		}

		// 点击删除的时候
		if (v == btnPhotoDelete) {

			final CustomDialog deleteDialog = new CustomDialog(
					PhotoDetailActivity.this);

			deleteDialog.setOnCancleClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					deleteDialog.dismiss();
				}
			});

			// 当点击确定的时候
			deleteDialog.setOnActionClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					int postion = vpPhotoViewPager.getCurrentItem();

					// 删除数据刷新列表
					PhotoDetailActivity.this.photos.remove(postion);

					// 刷新列表
					vpPhotoDetailViewPagerAdapter.notifyDataSetChanged();

					postion = vpPhotoViewPager.getCurrentItem();

					// 设置标题
					tvPhotoDetailTitle.setText("图片(" + (postion + 1) + "/"
							+ PhotoDetailActivity.this.photos.size() + ")");

					postion = vpPhotoViewPager.getCurrentItem();

					if (PhotoDetailActivity.this.photos.size() < 1) {

						returnData();
						// 终结生命周期
						finish();
					} else {
						Photo photo = photos.get(postion);

						cbShangChuan.setChecked(photo.isUpload());

						if (photo.getLatitude() != null
								&& photo.getLatitude() > 1
								&& photo.getLongitude() != null
								&& photo.getLongitude() > 1) {
							tvJingWei.setVisibility(View.VISIBLE);


							BigDecimal a = new BigDecimal(photo.getLongitude());
							double longite = a.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

							BigDecimal b = new BigDecimal(photo.getLatitude());
							double latitude = b.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

							tvJingWei.setText(longite + " , "+latitude);
						} else {

							tvJingWei.setText("未知 , 未知");
						}

					}

					deleteDialog.dismiss();
				}
			});

			deleteDialog.setMessage(getResources().getString(
					R.string.delete_message));

			deleteDialog.setCancleTxt(getResources().getString(
					R.string.jiandujiancha_item_cancle));

			deleteDialog.setActionTxt(getResources().getString(
					R.string.jiandujiancha_item_sure));

			deleteDialog.show();

		}

		// 点击详细信息的时候
		if (v == btnPhotoDetailInfo) {

			/**
			 * 文件信息的集合
			 */
			List<String> itemList = new ArrayList<String>();

			int postion = vpPhotoViewPager.getCurrentItem();

			Photo photo = photos.get(postion);

			Boolean noNetworkObj = photo.getNoNetwork();

			String timeInfo = "拍摄时间( ";

			/**
			 * 如果没有网络
			 */
			if (noNetworkObj != null && noNetworkObj) {
				timeInfo += "本地时间) : \n";
			} else {
				timeInfo += "网络时间) : \n";
			}

			String time = photo.getPhotoTime();

			if (time == null) {
				timeInfo += "未知";
			} else {
				timeInfo += time;
			}

			// 增加时间信息
			itemList.add(timeInfo);

			// 维度对象
			Object longitudeObj = photo.getLongitude();
			BigDecimal a = new BigDecimal(photo.getLongitude());
			double longite = a.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

			String longitudeInfo = "经度 : ";

			if (longitudeObj == null) {
				longitudeInfo += "未知";
			} else {
				longitudeInfo += longite+"";
			}
			// 增加纬度信息
			itemList.add(longitudeInfo);

			// 维度对象
			Object latitudeObj = photo.getLatitude();

			BigDecimal b = new BigDecimal(photo.getLatitude());
			double latitude = b.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();

			String latitudeInfo = "纬度 : ";
			if (latitudeObj == null) {
				latitudeInfo += "未知";
			} else {
				latitudeInfo +=latitude+"";
			}
			// 增加纬度信息
			itemList.add(latitudeInfo);

			// 位置信息
			Object descObj = photo.getAddressDesc();

			String descInfo = "位置信息(仅供参考) : \n";

			if (descObj == null) {
				descInfo += "未知";
			} else {
				descInfo += descObj.toString().trim();
			}
			// 增加地区信息
			itemList.add(descInfo);

			// 评论信息
			Object commentObj = photo.getComment();

			String commentInfo = "评论 : ";

			if (commentObj == null) {
				commentInfo += "";
			} else {
				commentInfo += commentObj.toString().trim();
			}
			// 增加评论信息
			itemList.add(commentInfo);

			// 相信信息对话框
			final CustomDialog photoDetailDialog = new CustomDialog(this);

			photoDetailDialog.setOnActionClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					photoDetailDialog.dismiss();
				}

			});

			photoDetailDialog.setHeightPercent(0.6F);
			photoDetailDialog.setActionTxt(getResources().getString(
					R.string.jiandujiancha_btn_sureitem));

			ViewGroup llDialogContentLayout = (ViewGroup) photoDetailDialog
					.findViewById(R.id.llDialogContentLayout);

			/*
			 * <View android:layout_width="match_parent"
			 * android:layout_height="1.5dp" android:background="#00B28C" />
			 */
			// 清理视图
			llDialogContentLayout.removeAllViews();

			for (String item : itemList) {

				TextView tvInfo = new TextView(this);

				int paddingLeft = Utils.dip2px(this, 10);

				tvInfo.setPadding(paddingLeft, paddingLeft, paddingLeft,
						paddingLeft);
				tvInfo.setText(item);

				tvInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

				tvInfo.setTextColor(Color.parseColor("#36495C"));

				tvInfo.setGravity(Gravity.CENTER_VERTICAL);

				llDialogContentLayout.addView(tvInfo, new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

				// 不是最后一个元素才绘制分割线
				if (itemList.indexOf(item) < itemList.size() - 1) {

					View separator = new View(this);
					separator.setBackgroundColor(Color.parseColor("#C4C3C1"));
					llDialogContentLayout.addView(separator, new LayoutParams(
							LayoutParams.MATCH_PARENT, 1));
				}

			}

			// 显示对话框
			photoDetailDialog.show();

		}

		// 当点击评论的时候
		if (btnComment == v) {

			// 初始化底部弹出的窗口
			final AlertDialog photoCommentDialog = new AlertDialog.Builder(
					new ContextThemeWrapper(PhotoDetailActivity.this,
							R.style.NongYeTongFullscreenTheme)).create();

			// 输入法的设置
			photoCommentDialog.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

			// 设置窗口的动画
			photoCommentDialog.getWindow().setWindowAnimations(
					R.style.bottomAnimStyle);

			// 此处可以设置dialog显示的位置 ,显示在底部
			photoCommentDialog.getWindow().setGravity(Gravity.BOTTOM);

			// 让底部的宽度和屏幕的宽度一致
			LinearLayout bottomPhotoCommentLayout = (LinearLayout) getLayoutInflater()
					.inflate(R.layout.bottom_photodetail_comment, null);

			bottomPhotoCommentLayout.setMinimumWidth(getWindowManager()
					.getDefaultDisplay().getWidth());

			photoCommentDialog.show();

			// 设置底部布局
			photoCommentDialog.setContentView(bottomPhotoCommentLayout);

			// 弹出输入法的操作
			photoCommentDialog.getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

			/*
			 * 输入的评论
			 */
			final EditText edtCommentPhoto = (EditText) photoCommentDialog
					.findViewById(R.id.edtCommentPhoto);

			// 返回按钮
			final ViewGroup btnBack = (ViewGroup) photoCommentDialog
					.findViewById(R.id.btnBack);

			// 确定评论按钮
			final ViewGroup btnSure = (ViewGroup) photoCommentDialog
					.findViewById(R.id.btnSure);

			// 获取当前图片的下标
			int postion = vpPhotoViewPager.getCurrentItem();

			final Photo photo = photos.get(postion);

			// 加载已经存在的评论
			String comment = photo.getComment();

			if (comment != null) {

				edtCommentPhoto.setText(comment);

				edtCommentPhoto.setFocusable(true);
				edtCommentPhoto.requestFocus();

				edtCommentPhoto.selectAll();

			}

			View.OnClickListener btnOnClickListener = new OnClickListener() {

				@Override
				public void onClick(View v) {

					// 当点击返回的时候
					if (v == btnBack) {
						photoCommentDialog.dismiss();
					}

					// 当点击确定的时候
					if (v == btnSure) {
						photo.setComment(edtCommentPhoto.getText().toString()
								.trim());

						photoCommentDialog.dismiss();
					}

				}
			};

			btnBack.setOnClickListener(btnOnClickListener);
			btnSure.setOnClickListener(btnOnClickListener);

		}
	}

	/**
	 * 当按下back案件的时候
	 */
	@Override
	public void onBackPressed() {
		returnData();

		super.onBackPressed();
	}

	/**
	 * 将数据返回
	 */
	private void returnData() {
		// 将数据返回
		Intent to_paizhao_intent = new Intent();
		to_paizhao_intent.putExtra("photos", (Serializable) photos);
		PhotoDetailActivity.this.setResult(
				PaiZhaoActivity.REQUEST_DETAIL_PHOTO_CODE, to_paizhao_intent);
	}

}
